package com.gator.rabbitmq.pablo_rabbitmq.boot.rabbitmq.config;

import org.springframework.amqp.core.*;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.HashMap;
import java.util.Map;

/**
 * @Author PABLO
 * @Date 2022/6/6 15:43
 * @Desc 插件实现延迟队列配置类
 */
@Configuration
public class DelayQueueConfig {
    //延迟交换机
    public static final String DELAY_EXCHANGE_NAME = "delay_exchange";
    //延迟队列
    public static final String DELAY_QUEUE_NAME = "delay_queue";
    //延迟路由key
    public static final String DELAY_ROUTING_KEY = "delay_routing_key";

    /**
     * @Description: 声明自定义插件交换机
     * @Author: PABLO
     * @Date: 2022/6/6 15:52
     * @Params: []
     * @Return: org.springframework.amqp.core.CustomExchange
     **/
    @Bean
    public CustomExchange delayExchange() {
        Map<String, Object> arguments = new HashMap<>();
        //延迟队列的类型是直接路由类型，因为延迟队列是按照指定的路由key进行消息分发的
        arguments.put("x-delayed-type", "direct");
        return new CustomExchange(DELAY_EXCHANGE_NAME,
                "x-delayed-message",
                true,
                false,
                arguments);
    }

    @Bean
    public Queue delayedQueue() {
        return QueueBuilder.durable(DELAY_QUEUE_NAME).build();
    }

    //绑定
    @Bean
    public Binding delayedBindingExchange(@Qualifier("delayExchange") CustomExchange delayExchange,
                                          @Qualifier("delayedQueue") Queue delayedQueue) {
        return BindingBuilder.
                bind(delayedQueue).
                to(delayExchange).
                with(DELAY_ROUTING_KEY)
                .noargs();
    }
}
